import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.util.PDFTextStripper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

public class PDFTextParser {

	PDFParser parser;
	String parsedText;
	PDFTextStripper pdfStripper;
	PDDocument pdDoc;
	COSDocument cosDoc;
	PDDocumentInformation pdDocInfo;

	public static void main(String args[]) throws IOException,
	ParserConfigurationException, SAXException {

		PDFTextParser pdfTextParserObj = new PDFTextParser();

		FileReader f = new FileReader(
				"J:\\BC3_IMT_Training\\annotations\\IMT_training_pmids.txt");
		BufferedReader fb = new BufferedReader(f);
		String name = fb.readLine();

		while (name != null) {
			File file = new File("J:\\BC3_IMT_Training\\text per page\\" + name);
			file.mkdir();
			int len = getPages(name);
			if (len == 0) {
				String s = "J:\\BC3_IMT_Training\\articles\\pdf\\" + name
						+ ".pdf";

				String out = file + "\\" + name + ".txt";

				String pdfToText = pdfTextParserObj.pdftoText(s,0);

				if (pdfToText == null) {
					System.out.println("PDF to Text Conversion failed.");
				} else {
					pdfTextParserObj.writeTexttoFile(pdfToText, out);
				}

			} else {

				String s = "J:\\BC3_IMT_Training\\articles\\pdf\\" + name
						+ ".pdf";

				int i = 1;
				while (i <= len) {
					String out = file + "\\" + i + ".txt";

					String pdfToText = pdfTextParserObj.pdftoText(s, i);

					if (pdfToText == null) {
						System.out.println("PDF to Text Conversion failed.");
					} else {
						pdfTextParserObj.writeTexttoFile(pdfToText, out);
					}

					i++;
				}

			}

			name = fb.readLine();
		}
	}

	String pdftoText(String fileName, int pgNumber) throws IOException {

		File f = new File(fileName);

		if (!f.isFile()) {
			System.out.println("File " + fileName + " does not exist.");
			return null;
		}

		try {
			parser = new PDFParser(new FileInputStream(f));
		} catch (Exception e) {
			System.out.println("Unable to open PDF Parser.");
			return null;
		}

		try {

			parser.parse();
			cosDoc = parser.getDocument();
			pdfStripper = new PDFTextStripper();
			pdDoc = new PDDocument(cosDoc);

			if(pgNumber!=0){
			pdfStripper.setStartPage(pgNumber);
			pdfStripper.setEndPage(pgNumber);
			
			}
         pdfStripper.setParagraphEnd("Paragraph End");
         parsedText = pdfStripper.getText(pdDoc);

		} catch (Exception e) {
			System.out
			.println("An exception occured in parsing the PDF Document.");
			e.printStackTrace();
			try {
				if (cosDoc != null)
					cosDoc.close();
				if (pdDoc != null)
					pdDoc.close();
			} catch (Exception e1) {
				e.printStackTrace();
			}
			return null;
		}
		cosDoc.close();
		return parsedText;
	}

	

	void writeTexttoFile(String pdfText, String fileName) {

		try {

			PrintWriter pw = new PrintWriter(fileName);

			pw.print(pdfText);
			pw.close();
		} catch (Exception e) {
			System.out
			.println("An exception occured in writing the pdf text to file.");
			e.printStackTrace();
		}
	}

	public static int getPages(String name)
			throws ParserConfigurationException, SAXException, IOException {
		DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
				.newInstance();

		DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
		Document doc = docBuilder
				.parse(new File("J:\\BC3_IMT_Training\\articles\\pubmed_xml\\"
						+ name + ".xml"));

		NodeList nPages = doc.getElementsByTagName("MedlinePgn");
		Element p = (Element) nPages.item(0);
		String pages = p.getTextContent();
		String one;
		String two;
		if (pages != "") {
			int in = pages.indexOf("-");
			int last = pages.length();
			char ch = pages.charAt(0);

			if (in == -1) {
				one = "0";
				two = "0";

			} else if (!Character.isAlphabetic(ch)) {
				one = pages.substring(0, in);
				two = pages.substring(in + 1, last);

			} else {
				one = pages.substring(1, in);
				two = pages.substring(in + 1, last);

			}

		} else {
			one = "0";
			two = "0";

		}
		int l2 = two.length();
		int l1 = one.length();
		int len = 0;
		int first = 0;
		int second = 0;
		if (one.equals("0")) {
			len = -1;
		} else if (l1 == l2
				|| l1 == 1
				|| (l2 == 3 && (one.startsWith("9") || one.startsWith("8")) && l1 == 2)
				|| (l2 == 4 && (one.startsWith("9") || one.startsWith("8")) && l1 == 3)) {
			first = Integer.parseInt(one);
			second = Integer.parseInt(two);
			len = second - first;
		} else {
			int diff = l1 - l2;
			String temp = one.substring(0, diff);

			String temptwo = temp + two;
			first = Integer.parseInt(one);
			second = Integer.parseInt(temptwo);
			len = second - first;
		}
		System.out.println(name + " " + one + " " + two + " " + len);

		return len + 1;
	}
}